<?php
/**
* 用户银行卡模块 工具类
*
* 用户银行卡模块 工具类
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Tool\Statistics;

use Log;
use Illuminate\Support\Facades\DB;
use App\Services\Tool\DataBase\SQL;
use App\Services\Tool\GeneralTool;
use Illuminate\Support\Facades\Mail;
use App\Services\UserService\bankList;

class UserBankTool{

	//判断用户是否已绑定银行卡
	function getUserBankCardCount($input){
		$input['state'] = 1;
		$count = SQL::count(['table'=>'user_bank_infos',
							           'where'=>$input]);
		return $count;
	}

	//获取用户银行卡信息
    function getUserBankCard($input){
        $bank = DB::table('user_bank_infos')
                ->where($input)
                ->orderBy('default','desc')
                ->first();
        $obj  = (object)array();
        if(!isset($bank)) return $obj;

        $obj->user_card_id = isset($bank->id) ? $bank->id.'' : '' ;
        $obj->card_holder  = isset($bank->card_holder) ? $bank->card_holder : '' ;
        $obj->bank_card_no = isset($bank->bank_card_no) ? $bank->bank_card_no : '' ;
        $obj->phone        = isset($bank->phone) ? $bank->phone : '';
        $obj->bank_name    = isset($bank->bank_name) ? $bank->bank_name : '' ;
        $obj->bank_branch  = isset($bank->bank_branch) ? $bank->bank_branch : '' ;
        $obj->prov         = isset($bank->prov) ? $bank->prov : '';
        $obj->city         = isset($bank->city) ? $bank->city : '';
        $obj->result   	   = isset($bank->result)?$bank->result:1;
        $obj->area         = isset($bank->area) ? $bank->area : '';
        $obj->result_str   = $this->getBankCardResultStr($obj->result);

        return $obj;
    }

    //获取银行卡认证结果
    function getBankCardResultStr($input){
    	switch($input){
    		case 1:
    			return '审核中';
    		case 2:
    			return '通过';
    		case 0:
    			return '未通过';
    		default:
    			return '';
    	}
    }

    //绑定银行卡
    function bindingUserBankCard($input){
    	$input['created_at'] = time();
    	$input['updated_at'] = time();
    	$result = SQL::insert(['table'  => 'user_bank_infos',
    						   'insert' => $input]);
    	return $result;
    }

    //修改银行卡信息
    function updateUserBankCard($input){
    	$result = SQL::update(['table'=>'user_bank_infos',
    						   'where'=>['user_id'=>$input['user_id'],
    						   			 'id'=>$input['user_card_id']],
    						   'update'=>['card_holder'  => $input['card_holder'],
                                          'bank_card_no' => $input['bank_card_no'],
                                          'phone'        => $input['phone'],
                                          'bank_name'    => $input['bank_name'],
                                          'bank_branch'  => $input['bank_branch'],
                                          'prov'         => $input['prov'],
                                          'city'         => $input['city'],
                                          'area'         => $input['area'],
                                          'updated_at'   => time()]]);
    	return $result;
    }

    /**
    	银行卡校验
     */
    //银行卡卡号持卡人校验
    function bankCardNoHolderVeryfy($input){
        $veryfy = $this->judgeBankCardIsTrueByLocalhost($input);
        switch($veryfy){
            case 'unknow':
                return $this->bankCardVeryfyPost($input);
            case 'success':
                return true;
            case 'fail':
                return false;
            default:
                return false;
        }
    }

    //添加银行卡校验记录
    function addBankCardVeryfyLog($input){
        $input['created_at'] = time();
        $result = SQL::insert(['table'  => 'bank_card_holder_veryfys',
                               'insert' => $input]);
        return $result;
    }

    //查询银行卡校验失败记录
    function bank_card_veryfy_fail_time($input){
        $today = strtotime(date('Y-m-d',time()));
        $end   = $today + 3600 * 24;
        $count = DB::table('bank_card_holder_veryfys')
                 ->where(['user_id' => $input['user_id']])
                 ->whereBetween('created_at',[$today,$end])
                 ->count();
        return $count >= env('Bank_CARD_VERYFY_FAIL_TIME');
    }

    //判断银行卡及持卡人是否已校验
    function judgeBankCardIsTrueByLocalhost($input){
        $state = SQL::pluck(['table' => 'bank_card_holder_veryfys',
                             'where' => ['bank_card_no' => $input['bank_card_no'],
                                         'card_holder'  => $input['card_holder']],
                             'pluck' => 'state']);
        if(!isset($state)) return 'unknow';
        if($state==1) return 'success';
        return 'fail';
    }

    //发送银行卡号持卡人校验
    function bankCardVeryfyPost($input){
        $arr['key']      = env('BANK_CARD_HOLDER_VERYFY_APPKEY');
        $arr['realname'] = urlencode($input['card_holder']);
        $arr['bankcard'] = $input['bank_card_no'];

        $data = GeneralTool::createLinkstring($arr);

        $result = GeneralTool::http_curl(env('BANK_CARD_HOLDER_VERYFY'),$data);

        if(isset($result['error_code'])&&$result['error_code']==0&&isset($result['result'])&&isset($result['result']['res'])){
            switch($result['result']['res']){
                case 1:
                	$this->addBankCardVeryfyLog(['bank_card_no'=> $input['bank_card_no'],
                                                 'card_holder' => $input['card_holder'],
                                                 'user_id'     => $input['user_id'],
                                                 'state'       => 1,
                                                 'created_at'  => time()]);

                    return true;
                case 2:
                default:
                	$this->addBankCardVeryfyLog(['bank_card_no'=> $input['bank_card_no'],
                                                 'card_holder' => $input['card_holder'],
                                                 'user_id'     => $input['user_id'],
                                                 'state'       => 0,
                                                 'created_at'  => time()]);

                    return false;
            }
        }else if(isset($result->error_code) && $result->error_code == '10012'){
            $this->SendToMail(['reg_id'    => '',
                               'type'      => 'bank_card',
                               'rece_user' => env('ORDER_RECE_EMAIL'),
                               'full_name' => '',
                               'tel'       => '',
                               'message'   => '银行卡实名验证接口可用次数不足，请尽快充值，以免影响Mytee服务']);
        }
        return false;
    }


    //银行卡列表
    function user_bank_list($input){
        $result = DB::table('user_bank_infos')
                  ->where(['user_id' => $input['user_id'],
                           'state'   => 1,
                           'result'  => 2])
                  ->orderBy('default', 'desc')
                  ->orderBy('created_at', 'desc')
                  ->select('id as user_card_id', 'bank_card_no', 'bank_name', 'default', 'card_type')
                  ->get();
        $withdraw_max = self::get_configs('withdraw_max');
        $withdraw_poundage = self::get_configs('withdraw_poundage');
        foreach($result as $re){
            $bank_info            = bankList::getBankNameForCard($re->bank_card_no);
            $re->bank_card_no     = self::bank_card_no_format($re->bank_card_no);
            $re->bank_name        = isset($bank_info['bank_name']) ? $bank_info['bank_name'] : '';
            $re->bank_logo        = isset($bank_info['bank_logo']) ? $bank_info['bank_logo'] : '';
            $re->bank_theme_color = bankList::imgColor($re->bank_logo);
            $re->card_type_str    = $re->card_type == 1 ? '储蓄卡' : '未知';
            $re->poundage         = $withdraw_poundage . '';
            $re->withdraw_max     = $withdraw_max . '';
        }
        return $result;
    }

    //获取用户银行卡信息
    function get_user_bank_card($input){
        $bank = DB::table('user_bank_infos')
                ->where($input)
                ->first();
        $obj  = (object)array();
        if(!isset($bank)) return $obj;
        $withdraw_max          = self::get_configs('withdraw_max');
        $withdraw_poundage     = self::get_configs('withdraw_poundage');
        $obj->user_card_id     = isset($bank->id) ? $bank->id.'' : '' ;
        $obj->bank_card_no     = isset($bank->bank_card_no) ? self::bank_card_no_format($bank->bank_card_no) : '' ;
        $bank_info             = bankList::getBankNameForCard($bank->bank_card_no);
        $obj->bank_logo        = isset($bank_info['bank_logo']) ? $bank_info['bank_logo'] : '';
        $obj->bank_name        = isset($bank_info['bank_name']) ? $bank_info['bank_name'] : '';
        $obj->bank_theme_color = bankList::imgColor($obj->bank_logo);
        $obj->default          = isset($bank->default) ? $bank->default : 0;
        $obj->card_type        = isset($bank->card_type) ? $bank->card_type : 1;
        $obj->card_type_str    = $bank->card_type == 1 ? '储蓄卡' : '未知';
        $obj->poundage         = $withdraw_poundage . '';
        $obj->withdraw_max     = $withdraw_max . '';

        return $obj;
    }

    //判断验证码是否可发
    function code_can_send($input){
        $result = DB::table('verfy_codes')
                  ->where(['user_id' => $input['user_id'],
                           'type'    => $input['type'],
                           'state'   => 1])
                  ->where('vail_time', '>', time())
                  ->first();
        if(isset($result)) return GeneralTool::createResult('','M06028');
        return GeneralTool::createResult('','M00000');
    }

    //保存验证码
    function save_code($input, $vail = 1){
        $data['user_id']    = $input['user_id'];
        $data['code']       = $input['code'];
        $data['type']       = $input['type'];
        $data['created_at'] = time();
        $data['updated_at'] = time();
        $data['vail_time']  = time() + $vail * 60;
        $result = SQL::insert(['table' =>  'verfy_codes',
                               'insert' => $data]);
        return $result;
    }

    //修改密码
    function update_user_widthdraw($where,$value){
        $result = SQL::update(['table' => 'users',
                               'where' => $where,
                               'update'=> $value]);
        return $result;
    }





    /**
     * 工具
     */
    //设置默认银行卡
    static function set_bank_card_default($input){
        SQL::update(['table' => 'user_bank_infos',
                     'where' => ['user_id' => $input['user_id'],
                                 'state'   => 1],
                    'update' => ['default' => 0]]);
        SQL::update(['table' => 'user_bank_infos',
                     'where' => ['id'      => $input['user_card_id'],
                                 'user_id' => $input['user_id'],
                                 'state'   => 1],
                     'update'=> ['default' => 1]]);
    }

    //打扫验证码
    function clearn_captcha($input){
        $code = SQL::update(['table' => 'verfy_codes',
                             'where' => $input,
                             'update'=> ['state' => 0]]);
        $code;
    }

    //验证验证码
    function verfy_captcha($input){
        $count  = self::user_fail_count($input);
        if($count >= env('VERFY_FAIL_TIME'))
            return GeneralTool::createResult('', 'M06033');
        $result = DB::table('verfy_codes')
                  ->where(['user_id' => $input['user_id'],
                           'type'    => $input['type'],
                           'state'   => 1])
                  ->where('vail_time', '>', time())
                  ->first();
        if(!isset($result)) return GeneralTool::createResult('', 'M06031');
        if($result->code != $input['code']){
            self::log_user_fail($input);
            return GeneralTool::createResult('', 'M06032');
        }
        return GeneralTool::createResult('', 'M00000');
    }
    //获取用户失败数
    static function user_fail_count($input){
        $count = DB::table('log_user_fail')
                 ->where(['user_id' => $input['user_id'],
                          'type'    => $input['type'],
                          'state'   => 1])
                 ->where('created_at', '>', time() - 3600)
                 ->count();
        return $count;
    }
    //记录用户
    static function log_user_fail($input){
        $data['user_id'] = $input['user_id'];
        $data['type']    = $input['type'];
        $data['created_at'] = time();
        SQL::insert(['table' => 'log_user_fail',
                     'insert'=> $data]);
    }

    //银行卡格式化
    static function bank_card_no_format($input){
        $len = mb_strlen($input, 'utf-8');
        return $len > 4 ? str_replace( mb_substr($input, 0, $len - 4) , '**** **** **** ', $input) : $input;
    }

    //密码加密
    static function md5pwd($pwd,$user_id){
        return md5($pwd . md5($user_id));
    }

    //获取配置
    static function get_configs($input){
        $val = SQL::pluck(['table' => 'configs',
                           'where' => ['name'  => $input,
                                       'state' => 1],
                           'pluck' => 'value']);
        return $val;
    }

    //判断用户提现密码是否正确
    static function verfy_withdraw_password($input){

        $val = SQL::count(['table' => 'users',
                           'where' => ['user_id' => $input['user_id'],
                                       'withdraw_password' => self::md5pwd($input['password'], $input['user_id'])]]);
        if($val == 0) self::log_user_fail(['user_id' => $input['user_id'], 'type' => $input['type']]);
        return $val;
    }

    //判断用户是否设置密码
    static function user_has_withdraw_password($input){
        $count = SQL::count(['table' => 'users',
                             'where' => ['user_id' => $input['user_id'],
                                         'withdraw_password' => '']]);
        return $count;
    }

    /**
        邮件
     */
    function SendToMail($input){
        //$email    = "547274138@qq.com";
        $username = "";
        try{
            $data = ['email'     => $input['rece_user'],
                     'full_name' => $input['full_name'],
                     'order_id'  => $input['reg_id'],
                     'tel'       => $input['tel'],
                     'username'  => $username,
                     'messages'  => $input['message']];
            //dd($data);
            Mail::send('activemail', $data, function ($message) use ($data) {
                $message->to($data['email'], $data['username'])->subject($data['messages']);
            });
            $result = SQL::insert(array('table'=>'email_records',
                              'insert'=>array('reg_id'     => $input['reg_id'],
                                              'type'       => $input['type'],
                                              'message'    => $input['message'],
                                              'rece_user'  => $input['rece_user'],
                                              'created_at' => time())));

            return true;
        }catch(\Exception $e){
            Log::info($e);
            return false;
        }
    }
}
